package client;

//~--- non-JDK imports --------------------------------------------------------

import com.dukascopy.api.Instrument;
import com.dukascopy.api.OfferSide;
import com.dukascopy.api.Period;
import com.dukascopy.api.system.ITesterClient;
import com.dukascopy.api.system.Overnights;
import com.dukascopy.api.system.TesterFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import strategies.*;

//~--- JDK imports ------------------------------------------------------------

import java.io.File;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

/**
 * This class encapsulates the strategy running through JForex tester client
 */
public class JForexMain {

    /**
     * System logger
     */
    static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    /**
     * Password
     */
    private static String password = "txKMG";

    /**
     * Login name
     */
    private static String userName = "DEMO2txKMG";

    /**
     * Strategy arguments
     */
    private static ArrayList<StrategyArgs> strategyArgs = new ArrayList<StrategyArgs>();

    /**
     * Strategy to be tested
     */
    public static Strategy strategy;

    /**
     * Tester client for testing strategies
     */
    private static ITesterClient testClient;

    /**
     * Main entry method
     * @param args strategy arguments
     * @throws Exception thrown for any reason
     */
    public static void main(String[] args) throws Exception {

        // Add the strategy args to list
      StrategyArgs args1 = new StrategyArgs(10, 900, 0, 1, Period.ONE_HOUR, "2009-06-01 00:00:00", "2011-05-09 23:59:59",
          30, 1000, .003, .01, .02, false);
      args1.setMinTakeProfit(300);
      strategyArgs.add(args1);

        // Create the tester client and connect to jforex demo platform
        testClient = TesterFactory.getDefaultInstance();

        String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";

        testClient.connect(jnlpUrl, userName, password);

        // Start the strategy
        strategy = new AdaptiveTakeProfitStrategy(strategyArgs.get(0));
        //strategy = new DummyStrategy(strategyArgs.get(0),true, "jf");
        runStrategy(strategy);
    }

    /**
     * Run the strategy supplied on JForex tester client
     * @param strategy to be run
     * @throws Exception any exception thrown which could not be handled
     */
    public static void runStrategy(Strategy strategy) throws Exception {

        // File name made up using strategy args
        String fileName = String.format("__%d_%d_%d_%s", strategy.arguments.getCandleThreshold(),
                                        ((int) strategy.arguments.getTakeProfit()),
                                        strategy.arguments.getMaxConsecutivePositions(),
                                        strategy.arguments.getPeriod().name());

        // set the listener that will receive system events
        MySystemListener mySystemListener = new MySystemListener(LOGGER, testClient, userName, password, fileName,
                                                strategyArgs, strategy);

        testClient.setSystemListener(mySystemListener);
        System.out.println("Strategy started at " + Calendar.getInstance().getTime());

        // subscribe to the instruments
        Set<Instrument> instruments = new HashSet<Instrument>();

        instruments.add(Instrument.EURUSD);
        System.out.println("Subscribing instruments...");
        testClient.setSubscribedInstruments(instruments);

        // Set the cache directory
        File cacheDir = new File("C:/Users/San/cache");

        // File cacheDir = new File("/home/sanjeev/cache");
        cacheDir.mkdirs();
        testClient.setCacheDirectory(cacheDir);

        // Set strategy parameters
        Calendar fromDate = Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"));
        Calendar toDate   = Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"));

        fromDate.setTime(strategy.arguments.getStartDate());    // min
        toDate.setTime(strategy.arguments.getEndDate());        // min
        System.out.println(fromDate.getTime());
        System.out.println(toDate.getTime());
        testClient.setDataInterval(Period.TICK, OfferSide.BID, ITesterClient.InterpolationMethod.FOUR_TICKS,
                                   fromDate.getTimeInMillis(), toDate.getTimeInMillis());
        testClient.setInitialDeposit(java.util.Currency.getInstance("USD"), strategy.arguments.getInitialDeposit());
        testClient.setLeverage(strategy.arguments.getLeverage());
        testClient.setMCEquity(0);    // this is a lower threshold. If the equity

        Overnights overnights = new Overnights(false);

        testClient.setOvernights(overnights);

        // goes below
        // this value, positions/orders are closed
        // Logging stuff
        testClient.setProcessingStatsEnabled(true);
        testClient.setEventLogEnabled(false);
        testClient.setGatherReportData(true);

        // start the strategy
        System.out.println("Starting strategy");
        testClient.startStrategy(strategy);
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
